package com.home.common.handler;

import com.home.base.core.framework.msg.PageResponse;
import com.home.base.core.framework.msg.ServerResponse;
import com.home.common.annotation.NotResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Description: 全局统一响应处理
 * Created by 王大宸 on 2020-09-23 0:46
 * Created with IntelliJ IDEA.
 */
@RestControllerAdvice(basePackages = {"com.home"})
public class ResponseAdviceHandler implements ResponseBodyAdvice<Object> {
    private static final Logger logger = LoggerFactory.getLogger(ResponseAdviceHandler.class);

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是 ServerResponse/PageResponse 那就没有必要进行额外的操作，返回false
        return !(returnType.getParameterType().equals(ServerResponse.class)
                || returnType.getParameterType().equals(PageResponse.class)
                || returnType.hasMethodAnnotation(NotResponseBody.class));
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装，所以要进行些特别的处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在 ServerResponse 里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(ServerResponse.okData(data));
            } catch (JsonProcessingException e) {
                logger.error("返回String类型错误: ", e);
                return ServerResponse.errMsg("返回String类型错误");
            }
        }
        // 将原本的数据包装在ServerResponse里
        return ServerResponse.okData(data);
    }
}
